import os
import shutil

from rest_framework.parsers import JSONParser
from core.response import CustomResponse
from file.services import knowbase_service, file_service, textvector_service, imagevector_service
from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from django.conf import settings
from file.models import KnowledgeBase
from django.db import transaction
from django.shortcuts import render


class KnowBaseViewSet(viewsets.ViewSet):
    permission_classes = [AllowAny]
    parser_classes = [JSONParser]
    @action(detail=False, methods=['GET'], url_path='list', url_name='list')
    def get_knowbase_list(self,request):
        knowbases = knowbase_service.get_all_know_bases()
        return CustomResponse.success(data = knowbases)

    @action(detail=False, methods=['GET'], url_path='list_html', url_name='list_html')
    def get_knowbase_html(self,request):
        knowbases = knowbase_service.get_all_know_bases()
        return render(request, 'file/knowbase_list.html', {'knowbases':knowbases})


    @action(detail=False, methods=['POST'], url_path='create', url_name='create')
    def create_knowbase(self,request):
        #从请求体body中获取数据
        knowbase_name = request.data.get('knowbase_name')
        knowbase_path = os.path.join(settings.MEDIA_ROOT, knowbase_name)
        knowbase = knowbase_service.get_knowbase_by_name(knowbase_name)
        if os.path.exists(knowbase_path) or knowbase is not None:
            return CustomResponse.error(message="当前知识库已存在，不允许重复创建")
        os.mkdir(knowbase_path)
        KnowledgeBase.objects.create(
            know_base_name=knowbase_name,
        )
        return CustomResponse.success(message = "知识库创建成功")

    @action(detail=False, methods=['DELETE'], url_path='delete', url_name='delete')
    def delete_knowbase(self,request):
        knowbase_id = request.data.get('knowbase_id')
        knowbase_name = request.data.get('knowbase_name')
        knowbase_path = os.path.join(settings.MEDIA_ROOT, knowbase_name)
        knowbase = knowbase_service.get_knowbase_by_id(knowbase_id)
        if not os.path.exists(knowbase_path) or not os.path.isdir(knowbase_path) or knowbase is None:
            return CustomResponse.error(message="删除失败，当前知识库不存在，请确认！")
        # todo: 当前的删除逻辑存在问题，可能存在文件系统和数据库系统不一致的情况，后续可以通过逻辑删除加定时任务进行优化
        # 给文件知识库数据表和文件数据表增加状态字段，用编码标记状态为有效和删除，调用接口时只将数据库字段标记为删除
        # 后续通过定时任务对标记删除的进行文件系统的删除
        try:
            shutil.rmtree(knowbase_path)
            with transaction.atomic():
                try:
                    knowbase_service.delete_knowbase_by_id(knowbase_id)
                    file_service.delete_files_by_knowbase_id(knowbase_id)
                    textvector_service.delete_by_knowbase_id(knowbase_id)
                    imagevector_service.delete_by_knowbase_id(knowbase_id)
                    return CustomResponse.success(message="当前知识库已删除！")
                except Exception as e:
                    return CustomResponse.error(message="当前知识库删除失败，原因为"+str(e))
        except Exception as e:
            return CustomResponse.error(message="当前知识库删除失败，原因为"+str(e))





